package com.indusfo.spc.service.impl;

import com.indusfo.spc.exception.GlobalException;
import com.indusfo.spc.exception.ModifyFailedException;
import com.indusfo.spc.exception.ParamsErrorException;
import com.indusfo.spc.mapper.AreaMapper;
import com.indusfo.spc.mapper.SiteMapper;
import com.indusfo.spc.mapper.UploadMapper;
import com.indusfo.spc.mapper.WarehouseMapper;
import com.indusfo.spc.pojo.Area;
import com.indusfo.spc.pojo.Site;
import com.indusfo.spc.pojo.Warehouse;
import com.indusfo.spc.service.WarehouseService;
import com.indusfo.spc.vo.CommonUtil;
import com.indusfo.spc.vo.JSONObject;
import com.indusfo.spc.vo.XTreeNode;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;


import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.List;

@Service
public class WarehouseServiceImpl implements WarehouseService {

    private  static  final Logger logger = LoggerFactory.getLogger(WarehouseServiceImpl.class);

    @Resource
    private WarehouseMapper warehouseMapper;

    @Resource
    private AreaMapper areaMapper;

    @Resource
    private SiteMapper siteMapper;

    @Resource
    private UploadMapper uploadMapper;

    /**
     * 查询
     * @param warehouse
     * @return
     */
    @Override
    public JSONObject selectWarehouse(Warehouse warehouse) {
        List<Warehouse> warehouseList = null;
        int count = 0;
        try {
            Integer pagesize = warehouse.getPagesize();
            Integer pageindex = warehouse.getPageindex();
            if(pagesize != null && pageindex != null) {
                warehouse.setIncept(pagesize*(pageindex - 1));
            }
            warehouseList = warehouseMapper.selectWarehouse(warehouse);
            //查询分页总记录数
            count = warehouseMapper.countWarehouse(warehouse); //返回查询到的总记录数
            if (warehouseList.isEmpty()) {
                return JSONObject.oK("没有查询到相关数据", warehouseList, count);
            }
            return JSONObject.oK("查询成功", warehouseList, count);
        } catch (
        GlobalException e) {
            logger.error(e.getMessage(), e);
            return JSONObject.build(403, e.getMessage());
        }
    }

    /**
     * 新增
     * @param warehouse
     * @return
     */
    @Override
    public JSONObject insertWarehouse(Warehouse warehouse) {
        try {
            if(warehouse.getWarehouseId()!= null) {
                throw new ParamsErrorException("新增时，不能填写id");
            }
            checkParam(warehouse);
            // 调用存储过程
            int row = warehouseMapper.insertSelective(warehouse);
            if(row == 0) {
                throw new ModifyFailedException("数据新增失败");
            }
            return JSONObject.oK("新增成功");
        } catch (GlobalException e) {  //这里只捕获自定义异常
            logger.error(e.getMessage(), e);
            return JSONObject.build(403, e.getMessage());
        }
    }

    /**
     * 修改
     * @param warehouse
     * @return
     */
    @Override
    public JSONObject updateWarehouse(Warehouse warehouse) {
        try {
            if(warehouse.getWarehouseId()== null) {
                throw new ParamsErrorException("请选择要更新的仓库");
            }
            checkParam(warehouse);
            // 调用存储过程
            int row = warehouseMapper.updateByPrimaryKeySelective(warehouse);
            if(row == 0) {
                throw new ModifyFailedException("数据编辑失败");
            }
            return JSONObject.oK("编辑成功");
        } catch (GlobalException e) {  //这里只捕获自定义异常
            logger.error(e.getMessage(), e);
            return JSONObject.build(403, e.getMessage());
        }
    }

    /**
     * 停用启用删除
     * @param warehouseIds
     * @param dataState
     * @return
     */
    @Override
    public JSONObject definedWarehouse(Long[] warehouseIds, Integer dataState) {
        try {
            if(dataState == null) {
                throw new ParamsErrorException("数据状态不能为空");
            }else if(dataState != 1 && dataState != 2 && dataState != 3) {
                throw new ParamsErrorException("数据状态错误");
            }
            if (warehouseIds == null) {
                throw new ParamsErrorException("id不能为空");
            }
            if(dataState == 2 || dataState == 3){
                for(Long warehouseId : warehouseIds ) {
                    List<Area> areaList = areaMapper.getByWarehouseId(warehouseId.intValue());
                    if(areaList.size() != 0){
                        if(dataState == 2) {
                            throw new ParamsErrorException("仓库下有区域,删除失败");
                        } else if(dataState == 3) {
                            throw new ParamsErrorException("仓库下有区域,停用失败");
                        }
                    }
                }
            }
            // 执行存储过程
            int row = warehouseMapper.definesWarehouse(warehouseIds, dataState);
            String msg = "";
            if (row == 0) {
                // 判断传入的数据状态参数lDataState,返回相应信息
                switch (dataState) {
                    case 1:
                        throw new ModifyFailedException("启用失败");
                    case 2:
                        throw new ModifyFailedException("删除失败");
                    case 3:
                        throw new ModifyFailedException("停用失败");
                    default:
                }
            } else {
                switch (dataState) {
                    case 1:
                        msg = "启用成功";break;
                    case 2:
                        msg = "删除成功";break;
                    case 3:
                        msg = "停用成功";break;
                    default:
                }
            }
            return JSONObject.oK(msg);
        } catch (GlobalException e) {
            logger.error(e.getMessage(), e);
            return JSONObject.build(403, e.getMessage());
        }
    }

    /**
     * 查询树
     * @return
     */
    @Override
    public JSONObject queryTree() {
        try {
            List<XTreeNode> nodes = new ArrayList<>();
            List<Warehouse> warehouseList = warehouseMapper.selectWarehouse(null);
            List<Area> areaList = new ArrayList<Area>();
            if (null != warehouseList) {
                for (Warehouse _warehouse : warehouseList) {
                    XTreeNode node = new XTreeNode();
                    node.setId(_warehouse.getWarehouseId()+"W");
                    node.setpId(null);
                    node.setOpen(true);
                    node.setFlag("cangku");
                    node.setTitle(_warehouse.getWarehouseName());
                    nodes.add(node);

                    List<Area> lines = areaMapper.getByWarehouseId(_warehouse.getWarehouseId());
                    areaList.addAll(lines);
                }
            }
            List<Site> siteList = new ArrayList<Site>();
            for(Area _Line:areaList){
                XTreeNode node = new XTreeNode();
                node.setId(_Line.getAreaId()+"A");
                node.setpId(_Line.getWarehouseId()+"W");
                node.setOpen(true);
                node.setFlag("quyu");
                node.setTitle(_Line.getAreaName());
                nodes.add(node);
                List<Site> list = siteMapper.getByAreaId(_Line.getAreaId());
                siteList.addAll(list);
            }
            for(Site _Site:siteList){
                XTreeNode node = new XTreeNode();
                node.setId(_Site.getSiteId()+"S");
                node.setpId(_Site.getAreaId()+"A");
                node.setOpen(true);
                node.setFlag("kuwei");
                node.setTitle(_Site.getSiteName());
                nodes.add(node);
            }
            List<XTreeNode> tree = CommonUtil.getTree(nodes, null);
            return JSONObject.oK(tree);
        } catch (ParamsErrorException e) {
            //返回封装异常信息的JSONObject给前端
            return JSONObject.build(404, e.getMessage());
        } catch (ModifyFailedException e) {
            return JSONObject.build(404, e.getMessage());
        }
    }

    @Override
    public String checkNoRepeatExcel(Warehouse warehouse) {
        if(StringUtils.isEmpty(warehouse.getWarehouseCode()) && StringUtils.isEmpty(warehouse.getWarehouseName())){
            return "该行数据为空/删除不彻底";
        }
        if (StringUtils.isEmpty(warehouse.getWarehouseCode())) {
           return "仓库编码为空";
        }
        if (warehouse.getWarehouseCode().getBytes().length > 50) {
            return "仓库编码超过规定,长度50";
        }
        if (StringUtils.isEmpty(warehouse.getWarehouseName())) {
            return "仓库名称为空";
        }
        if (warehouse.getWarehouseName().getBytes().length > 50) {
            return "仓库名称超过规定,长度50个字节,25个汉字";
        }
        // 编码不能重复
        Integer depCounts = warehouseMapper.queryWarehouse(warehouse);
        if (depCounts !=0) {
            return "该仓库编码已存在";
        }
        // 名称不能重复
        Integer warehouseCounts = warehouseMapper.queryWarehouseName(warehouse);
        if (warehouseCounts !=0) {
            return "该仓库名称已存在";
        }
        return null;
    }

    @Override
    public JSONObject updateListWarehouse(List<Warehouse> warehouseList) {
        uploadMapper.updateListWarehouse(warehouseList);
        return null;
    }


    /**
     * 参数校验
     */
    private void checkParam(Warehouse warehouse) {
//        if (bldc.getBldctypeId() == null) {
//            throw new ParamsErrorException("不良对策类型不能为空");
//        }
        if (StringUtils.isEmpty(warehouse.getWarehouseCode())) {
            throw new ParamsErrorException("请填写仓库编码");
        }
        if (warehouse.getWarehouseCode().getBytes().length > 50) {
            throw new ParamsErrorException("仓库编码超过规定,长度50");
        }
        if (StringUtils.isEmpty(warehouse.getWarehouseName())) {
            throw new ParamsErrorException("请填写仓库名称");
        }
        if (warehouse.getWarehouseName().getBytes().length > 50) {
            throw new ParamsErrorException("仓库名称超过规定,长度50");
        }
        // 编码不能重复
        Integer depCounts = warehouseMapper.queryWarehouse(warehouse);
        if (depCounts !=0) {
            throw new ParamsErrorException("该仓库编码已存在");
        }
        // 名称不能重复
        Integer warehouseCounts = warehouseMapper.queryWarehouseName(warehouse);
        if (warehouseCounts !=0) {
            throw new ParamsErrorException("该仓库名称已存在");
        }
    }

}
